iT邦幫忙

2025 iThome 鐵人賽

DAY 9
0

Mix 工具

mix 是一個管理 Elixir 的工具,裝完 Elixir 終端機也會有 mix 指令可以執行

mix 提供了我們一個統一的架構來建立、管理套件、測試、部署 Elixir 程式

mix new

使用 mix new 再加上專案名稱來建立一個新的專案

mix new hello_world
* creating README.md
* creating .formatter.exs
* creating .gitignore
* creating mix.exs
* creating lib
* creating lib/hello_world.ex
* creating test
* creating test/test_helper.exs
* creating test/hello_world_test.exs

Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:

    cd hello_world
    mix test

Run "mix help" for more commands.

長出來的資料結構長這樣

.
├── .formatter.exs
├── .gitignore
├── lib
│   └── hello_world.ex
├── mix.exs
├── README.md
└── test
    ├── hello_world_test.exs
    └── test_helper.exs
  • lib 資料夾是我們放主程式的地方
  • test 資料夾是放測試的地方,通常會跟 lib 資料夾匹配
  • mix.exs 是設定專案細節與管理套件的檔案
  • .formatter.exs 為 format 設定

mix.exs 檔案

新產生出來的 mix.exs 檔案,原本就有附上一些關於 applicationdeps 函式註解
不過目前來說,先知道 deps 是裝額外套件的地方

另外 Elixir 不像其他語言有 main 函式之類的起始點,後面在 OTP 的章節會一起解釋
在這個階段先使用 mix -S iex 來進入有包含這個專案的 iex 互動介面來執行目前講解的內容。

defmodule HelloWorld.MixProject do
  use Mix.Project

  def project do
    [
      app: :hello_world,
      version: "0.1.0",
      elixir: "~> 1.18",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  # Run "mix help compile.app" to learn about applications.
  def application do
    [
      extra_applications: [:logger]
    ]
  end

  # Run "mix help deps" to learn about dependencies.
  defp deps do
    [
      # {:dep_from_hexpm, "~> 0.3.0"},
      # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
    ]
  end
end

其他超常用的 mix 指令

使用 mix help 可以列出現在所有的指令

這個階段或是工作時常用的有

  • mix deps.get 安裝 deps 列出的套件

  • mix test 執行測試

  • mix format 自動編排程式

  • mix compile 編譯目前程式

  • iex -S mix 在 iex 開啟目前程式並掛進 iex 互動介面


上一篇
控制流程
下一篇
單元測試
系列文
通勤看手機就可讀懂的 Elixir 語言入門教學10
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言